'use strict';

const Controller = require('egg').Controller;

const sequelize = require('sequelize').Sequelize;
const Op = sequelize.Op;

class BookController extends Controller {
    constructor(ctx) {
        super(ctx);
    }

    async list() {
        const { ctx } = this;

        const pageNo = Number(ctx.query.pageNo || 1);
        const pageSize = Number(ctx.query.pageSize || 20);

        const result = await ctx.service.book.list(pageNo, pageSize);
        ctx.body = result
    }

    async add() {
        const { ctx, config } = this;
        let request = ctx.request.body;
        let user = ctx.state.user;
        if (user.role === 'customer') {
            ctx.throw(403, "用户权限不足！");
        }

        const result = await ctx.service.book.add(request);
        ctx.body = result
    }

    async update() {
        const { ctx, config } = this;
        let request = ctx.request.body;
        let user = ctx.state.user;
        if (user.role === 'customer') {
            ctx.throw(403, "用户权限不足！");
        }
        const result = await ctx.service.book.update(request);
        ctx.body = result
    }

    async delete() {
        const { ctx, config } = this;
        let user = ctx.state.user;
        if (user.role === 'customer') {
            ctx.throw(403, "用户权限不足！");
        }

        const { id } = ctx.query;
        const result = await ctx.service.book.delete(Number(id));
        ctx.body = result
    }

    async onSaleChange() {
        const { ctx, config } = this;
        let { id } = ctx.query;
        let user = ctx.state.user;
        if (user.role === 'customer') {
            ctx.throw(403, "用户权限不足！");
        }
        const result = await ctx.service.book.onSaleChange(id);
        ctx.body = result
    }

}

module.exports = BookController;

